import cv2


def face_recognition():
    print("正在打开摄像头...\n")
    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    font = cv2.FONT_HERSHEY_SIMPLEX

    #创建一个训练器
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    faceCascade = cv2.CascadeClassifier("E:\python\Lib\site-packages\cv2\data/haarcascade_frontalface_alt2.xml")

    #加载训练好的文件，用来识别
    recognizer.read('people.yml')

    while True:
        #ok：表示是否有读到数据；img：读到的图片数据放在img里面
        ok,img = cap.read()
        if not ok:
            break
        #镜像翻转
        img = cv2.flip(img,1)
        #将彩色照片转换成灰度图片
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        #人脸检测：用灰度图片进行检测，1.2和3分别为图片缩放比例和需要检测的有效点数，32*32为最小检测的图像像素
        faceRects = faceCascade.detectMultiScale(gray, scaleFactor = 1.5  , minNeighbors = 3, minSize = (128, 128))
        #如果有脸，把脸框出来
        for faceRect in faceRects:  #框出每一张人脸
            x, y, w, h = faceRect        
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            id,con = recognizer.predict(gray[y:y+h,x:x+w])
            if id == 13:
                name = "zyy"
                #cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                cv2.putText(img,str(con),(x + w-50 , y - 10),font,1,(0,0,255),1)
            else:
                name = "unkown" 
                #cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) 
                cv2.putText(img,name,(x + w-50 , y - 10),font,1,(0,0,255),1)
        #imshow是OpenCV带的窗口，video是窗口名字（可自取），img是要显示的图片数据
        cv2.imshow('video',img)

        #延时
        key = cv2.waitKey(1)
        if key == 27: #esc按键
            break

    cap.release()
    #释放摄像头
    cv2.destroyAllWindows()
    #关闭窗口
if __name__ == "__main__": 
    face_recognition()
